package com.rms.rmd.jdbc;

import java.io.FileInputStream;
import java.sql.Connection;
import java.util.Properties;

import org.apache.tomcat.jdbc.pool.DataSource;
import org.apache.tomcat.jdbc.pool.PoolProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DataSourceConnection {
    private static Logger _log = LoggerFactory.getLogger(DataSourceConnection.class);
    
    private static DataSource datasource = null;
 
    DataSourceConnection() {
    }
 
    public static Connection getConnection() {
        try {
            if (datasource == null) {
            	DataSourceConnection.initDatasource();
            }
            return datasource.getConnection();
        } catch (Exception e) {
        	_log.error(e.getMessage(), e);
            return null;
        }
    }
 
    public static void initDatasource() throws Exception {
 
		//Reading properties file
	    Properties props = new Properties();
	    FileInputStream fis = new FileInputStream("config/daemon-config.xml");

	    //loading properites from properties file
	    props.loadFromXML(fis);
	    fis.close();
	    
		// read files
		String url = props.getProperty("daemon.db.url").trim();    	
		String driverClassName = props.getProperty("daemon.db.driverClassName").trim();    	
		String userName = props.getProperty("daemon.db.userName").trim();    	
		String password = props.getProperty("daemon.db.password").trim();    	

        PoolProperties p = new PoolProperties();
 
        p.setUrl(url);
        p.setDriverClassName(driverClassName);
        p.setUsername(userName);
        p.setPassword(password);
 
        p.setJmxEnabled(true);
        p.setTestWhileIdle(false);
        p.setTestOnBorrow(true);
        p.setValidationQuery("SELECT 1");
        p.setTestOnReturn(false);
        p.setValidationInterval(30000);
        p.setTimeBetweenEvictionRunsMillis(30000);
 
        p.setMaxActive(1);
        p.setMaxIdle(1);
        p.setInitialSize(1);
        p.setMaxWait(10000);
        p.setRemoveAbandonedTimeout(300);
        p.setMinEvictableIdleTimeMillis(30000);
        p.setMinIdle(1);
 
        p.setLogAbandoned(true);        
        p.setRemoveAbandoned(true);
 
        p.setJdbcInterceptors("org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;"
                + "org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer");
 
        datasource = new DataSource();
        datasource.setPoolProperties(p);
 
    }
 
    public static void closeDatasource() {
        datasource.close();
    }
}